// pages/headerSchool/headerSchool.js
var QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
Page({

  data: {
    modalCtrl: 'hidden',
    briefIntroduction: '',
    drivingSchoolName: '',
    levelName: '',
    // picCount: 0,
    score: 0,
    titlePic: '',
    topPic: '',
    subList: [],
    attention: false,
    schoolId: '',
    lng: '',
    lat: '',
    latitude: '',
    longitude: '',
    address: '',
    pics: [],
    picsLength: 0,
  },
  onLoad: function(options) {
    // console.log(options);
    //获取总校图片列表
    this.getHeaderPics(options.tid).then(res=>{
      // console.log(res);
      //处理图片集合
      if(res.data.code == 0 && res.data.message == "成功"){
        let picsArr = res.data.data;
        let _picsArr = [];
        for(let i of picsArr){
          _picsArr.push(i.pics);
        }
        let _pics = [].concat(..._picsArr);
        // console.log(_pics);
        this.setData({
          pics: _pics,
          picsLength: _pics.length,
        })
      }

    }).catch(err=>{
      console.warn(err);
    })
    this.setData({
      schoolId: options.tid
    });
    let p1 = this.getLocationPromise();
    this.getSchoolInfoPromise(options.tid).then(result => {
      // console.log(result);
      if (result.data.code == 0 && result.data.message == '成功') {
        p1.then((res) => {
          // console.log(res);
          this.setData({
            lat: res.latitude,
            lng: res.longitude,
          })
          // console.log(this.data.lat)
          // console.log(this.data.lng);
          const newSubList = [];
          let subList = result.data.data.subList;
          // let subList = [{
          //     address: '南宁市大学东路188号',
          //     id: 0,
          //     latitude: 22.839866,
          //     longitude: 108.305766,
          //     name: '东风驾校1'
          //   },
          //   {
          //     address: '南宁市西乡塘',
          //     id: 1,
          //     latitude: 22.836869,
          //     longitude: 108.298911,
          //     name: '东风驾校2'
          //   }
          // ];
          for (let i of subList) {
            let t = Object.assign({}, i);
            let _lat = i.latitude;
            let _lng = i.longitude;

            let _distance = this.getDistance(this.data.lat, this.data.lng, _lat, _lng);
            // console.log(_distance);
            // let distance = parseFloat(i.distance);
            if (_distance >= 1000) {
              t._distance = (_distance / 1000).toFixed(1) + 'km';
            } else {
              t._distance = _distance + 'm';
            }
            newSubList.push(t);

          }
          this.setData({
            drivingSchoolName: result.data.data.name,
            levelName: result.data.data.levelName,
            briefIntroduction: [result.data.data.briefIntroduction],
            picCount: result.data.data.picCount,
            score: result.data.data.score,
            titlePic: result.data.data.titlePic,
            topPic: result.data.data.topPic,
            subList: newSubList,
          })
        }).catch((error) => {
          console.warn(error);
        });
      }
    }).catch(err => {
      console.warn(err);
    });
  },
  onReady: function() {

  },
  testModal(e) {
    // this.setData({
    //   modalCtrl: 'show'
    // })
    let _lat = e.currentTarget.dataset.lat;
    let _lng = e.currentTarget.dataset.lng;
    // console.log(e);
    this.getMap(_lat, _lng);
  },
  onCloseEvent() {
    this.setData({
      modalCtrl: 'hidden'
    })
  },
  handleMap() {
    wx.navigateTo({
      url: '../../pages/mapShow/mapShow',
    })
  },
  getSchoolInfoPromise(_optionsId) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://www.haitunxueche.com/student/index/getSchoolInfoVo',
        data: {
          id: _optionsId,
        },
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'GET',
        dataType: 'json',
        success: (result) => {
          resolve(result);
        },
        fails: (res) => {
          console.warn(res);
          reject(res);
        },
        complete: () => {}
      })
    })
  },
  getDistance: function(lat1, lng1, lat2, lng2) { // 计算距离
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;
    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    return (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))).toFixed(0)
  },
  getLocationPromise() {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        success: (res) => {
          resolve(res)
        }
      })
    })
  },
  getMap(_lat,_lng){
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: (res) => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        });
        var myAmap = new QQMapWX({ key: 'HTQBZ-FN3WI-IIRG7-5JWI4-74OFZ-AYFFJ' });
        // 调用接口
        myAmap.reverseGeocoder({
          location: {
            latitude: _lat,
            longitude: _lng,
          },
          success: (res)=> {
            console.log(res);
            if(res.status == 0){
              let _address = res.result.address;
              console.log(_address);
              wx.openLocation({
                latitude: _lat,
                longitude: _lng,
                name: _address,
                scale: 28
              })
            }
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            console.log(res);
          }
        });
      }
    })
  },
  getHeaderPics(_optionsId){
    return new Promise((resolve,reject)=>{
      wx.request({
        url: 'https://www.haitunxueche.com/student/index/getSchoolPicsVo',
        data: {
          id: _optionsId,
        },
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'GET',
        dataType: 'json',
        success: (result) => {
          resolve(result);
        },
        fails: (res) => {
          console.log(res);
          reject(res);
        },
        complete: () => { }
      })
    })
  },
  handlePic(e) {
    let picArr = this.data.pics;
    wx.navigateTo({
      url: '../drivingSchoolPic/drivingSchoolPic?picArr=' + picArr,
    })
  },
})